#是否交易时段
from datetime import datetime, timezone
import time
import pytz
import requests


def get_current_date():
    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为纽约时区
    ny_date = utc_now.astimezone(pytz.timezone('America/New_York'))
    date_str = ny_date.strftime('%Y-%m-%d')
    return date_str


def get_current_date_format(format):
    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为纽约时区
    ny_date = utc_now.astimezone(pytz.timezone('America/New_York'))
    date_str = ny_date.strftime(format)
    return date_str


def get_current_time():
    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为纽约时区
    ny_time = utc_now.astimezone(pytz.timezone('America/New_York'))
    return ny_time


def is_trading_hours():
    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为纽约时区
    ny_time = utc_now.astimezone(pytz.timezone('America/New_York'))
    # 检查是否为工作日（周一至周五）
    if ny_time.weekday() >= 5:  # 5=周六, 6=周日
        return False
    # 检查是否在交易时段内
    start_time = ny_time.replace(hour=9, minute=30, second=0, microsecond=0)
    end_time = ny_time.replace(hour=16, minute=0, second=0, microsecond=0)
    return start_time <= ny_time <= end_time


#是否盘后
def is_trading_after():
    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为纽约时区
    ny_time = utc_now.astimezone(pytz.timezone('America/New_York'))
    # 检查是否为工作日（周一至周五）
    if ny_time.weekday() >= 5:  # 5=周六, 6=周日
        return False
    end_time = ny_time.replace(hour=16, minute=0, second=0, microsecond=0)
    return ny_time > end_time


def ge_time(hour, minute):
    # 获取当前UTC时间
    utc_now = datetime.now(timezone.utc)
    # 转换为纽约时区
    ny_time = utc_now.astimezone(pytz.timezone('America/New_York'))
    end_time = ny_time.replace(hour=hour, minute=minute, second=0, microsecond=0)
    return ny_time >= end_time


def is_within_num_days(date1_str, date2_str, num, date_format="%Y-%m-%d"):
    """
    判断两个日期字符串是否相差2天以内

    参数:
        date1_str: 第一个日期字符串
        date2_str: 第二个日期字符串
        date_format: 日期字符串的格式，默认是"%Y-%m-%d"

    返回:
        bool: 如果相差2天或以内返回True，否则返回False
    """
    try:
        # 将字符串转换为datetime对象
        date1 = datetime.strptime(date1_str, date_format)
        date2 = datetime.strptime(date2_str, date_format)

        # 计算两个日期的差值（绝对值）
        delta = abs((date1 - date2).days)

        # 判断是否在2天以内（包括2天）
        return delta <= num
    except ValueError:
        # 处理日期格式错误
        print(f"错误：日期格式不符合要求，请使用{date_format}格式")
        return False


def get_market_status():
    url = "http://ths-fuyao-app-component-exchange-state-112782:8080/exchange/v1/market_status?market=168"
    start_time = time.time()  # 记录开始时间
    try:
        response = requests.get(url=url, timeout=10)
        elapsed_time = time.time() - start_time
        print(f"请求url:{url},请求状态：{response.status_code},请求耗时: {elapsed_time:.4f} 秒")
        response.raise_for_status()  # 检查请求是否成功（状态码 200）
        result_data = response.json()
        if result_data.get("status_code") != 0:
            print.error(f"response is :{result_data},API请求失败: {result_data.get('status_msg')}")
            return None
        return result_data
    except Exception as e:
        print("HTTP请求异常:", e)


def date_to_milliseconds_timestamp(date_str, date_format):
    # 解析日期字符串为datetime对象
    date_obj = datetime.strptime(date_str, date_format)
    # 转换为秒级时间戳，再乘以1000得到毫秒级
    timestamp_ms = int(date_obj.timestamp() * 1000)
    return timestamp_ms
    
def date_noon_timestamp(date_str, date_format='%Y-%m-%d', tz: str = 'UTC', milliseconds: bool = True):
    tzinfo = pytz.timezone(tz)
    # 仅保留日期部分, 构建中午时间
    d = datetime.strptime(date_str, date_format)
    local_noon = tzinfo.localize(datetime(d.year, d.month, d.day, 12, 0, 0))
    ts = local_noon.timestamp()
    return int(ts * 1000) if milliseconds else int(ts)